// pages/customer-edit/customer-edit.js
import apiConfig from '../../utils/apiConfig';
import http from '../../utils/http.js';
Page({
  data: {
    formData: {
        id: '',
        customer_name: '',
        customer_phone: '',
        another_name: '',
        county: '',
        town: '',
        village: '',

      },
    counties: [],
    towns: [],
    villages: [],
    selectedCounty: null,
    selectedTown: null,
    selectedVillage: null,
    selectedCountyIndex: -1,
    selectedTownIndex: -1,
    selectedVillageIndex: -1,
    
  },
  onLoad(options) {
    const id = options.id;
    this.setData({ currentId: id });
    this.loadCounties().then(() => {
      this.getCustomerInfo(id);
    });
  },

  // 加载县数据
  loadCounties() {
    return http.request({
      url: '/api/getCounties',
      method: 'GET'
    }).then(res => {
      if (res.status === 200) {
        this.setData({
          counties: res.data.map(item => ({
            id: item.id,
            address_name: item.address_name
          }))
        }, () => {
          console.log('县数据加载完成:', this.data.counties);
        });
      }
      return res;
    }).catch(err => {
      console.error('县数据加载失败:', err);
      throw err;
    });
  },


  onReady() {},
  getCustomerInfo(id) {
    http.request({
      url: apiConfig.getCustomerInfo,
      method: 'GET',
      data: { id },
    }).then(res => {
      if (res.status === 200) {
        const { id, customer_name, customer_phone, another_name, county, town, village, team } = res.data;
        this.setData({
          formData: {
          id: '',
          customer_name,
          customer_phone,
          another_name,
          county,
          town,
          village,

        },

            selectedCounty: this.data.counties.find(item => item.id === county) || null,
          selectedCountyIndex: this.data.counties.findIndex(item => item.id === county),
        }, () => {
          const selectedCounty = this.data.selectedCounty;
          if (selectedCounty) {
            this.loadTowns(selectedCounty.id, town, () => {
              const selectedTown = this.data.selectedTown;
              if (selectedTown) {
                this.loadVillages(selectedTown.id, this.data.formData.village);
              }
            });
          }
        });
      }
    })
  },

  // 带初始化的镇数据加载
  loadTowns(provinceId, townId, callback) {
    http.request({
      url: '/api/getCities',
      method: 'GET',
      data: { provinceId: provinceId }
    }).then(res => {
      if (res.status === 200) {
        this.setData({ towns: res.data }, () => {
          console.log(`县 ID ${provinceId} 的镇数据加载完成:`, this.data.towns);
          // 初始化镇选择
          if (townId && this.data.towns.length > 0) {
            const selectedTown = this.data.towns.find(item => item.id === townId);
            if (selectedTown) {
              const selectedTownIndex = this.data.towns.indexOf(selectedTown);
              this.setData({ selectedTown, selectedTownIndex }, () => {
                // 加载村数据并初始化村选择
                this.loadVillages(selectedTown.id, this.data.formData.village);
              });
            }
          }
        });
      }
    }).catch(err => {
      console.error('镇数据加载失败:', err);
    });
  },

  // 带初始化的村数据加载
  loadVillages(cityId, villageId, callback) {
    http.request({
      url: '/api/getDistricts',
      method: 'GET',
      data: { cityId: cityId }
    }).then(res => {
      if (res.status === 200) {
        this.setData({ villages: res.data }, () => {
          console.log(`镇 ID ${cityId} 的村数据加载完成:`, this.data.villages);
          // 初始化村选择
          if (villageId && this.data.villages.length > 0) {
            const selectedVillage = this.data.villages.find(item => item.id === villageId);
            if (selectedVillage) {
              const selectedVillageIndex = this.data.villages.indexOf(selectedVillage);
              this.setData({ selectedVillage, selectedVillageIndex });
            }
          }
        });
      }
    }).catch(err => {
      console.error('村数据加载失败:', err);
    });
  },
  onShow() {},
  bindCountyChange: function(e) {
    const index = e.detail.value;
    const selectedCounty = this.data.counties[index];
    this.setData({
      selectedCountyIndex: index,
      selectedCounty: selectedCounty,
      ['formData.county']: selectedCounty
    });
    // 加载镇数据并清空村数据
    if (selectedCounty && selectedCounty.id) {
      this.loadTowns(selectedCounty.id);
      this.updateCustomerAddress();
    }
  },

  bindTownChange: function(e) {
    const index = e.detail.value;
    const selectedTown = this.data.towns[index];
    this.setData({
      selectedTownIndex: index,
      selectedTown: selectedTown,
      ['formData.town']: selectedTown
    });
    // 加载村数据
    if (selectedTown && selectedTown.id) {
      this.loadVillages(selectedTown.id);
      this.updateCustomerAddress();
    }
  },

  bindVillageChange: function(e) {
    const index = e.detail.value;
    const selectedVillage = this.data.villages[index];
    this.setData({
      selectedVillageIndex: index,
      selectedVillage: selectedVillage,
      ['formData.village']: selectedVillage
    });
    this.updateCustomerAddress();
  },

  // 拼接地址并更新详细地址字段
  updateCustomerAddress() {
    const { county, town, village } = this.data.formData;
    const addressParts = [];
    if (county && county.address_name) addressParts.push(county.address_name);
    if (town && town.address_name) addressParts.push(town.address_name);
    if (village && village.address_name) addressParts.push(village.address_name);
    this.setData({
      ['formData.customer_address']: addressParts.join('')
    });
  },


  handleSubmit() {
    const that = this;
    const { selectedCounty, selectedTown, selectedVillage } = this.data;
    const customer_address = `${selectedCounty?.address_name || ''}${selectedTown?.address_name || ''}${selectedVillage?.address_name || ''}`;
    const formData = { 
      ...this.data.formData, 
      customer_address, 
      county: selectedCounty?.id || '',
      town: selectedTown?.id || '',
      village: selectedVillage?.id || ''
    };
    http.request({
      url: apiConfig.addCustomer,
      method: 'POST',
      data: formData
    }).then(res => {
      wx.showToast({
        title: '修改成功',
        icon: 'success'
      });
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      prevPage.onShow();
      wx.navigateBack();
    }).catch(err => {
      console.error('提交失败:', err);
      wx.showToast({
        title: err.message || '提交失败',
        icon: 'none'
      });
    });
  }
})